import React from "react";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
// import "../style/style.less";
import ThePagination from "@/components/ThePagination";
import {
  apiGetGoodsInfoPages,
  apiGetGoodsInfoPutaway,
  apiGetGoodsInfoRecommend,
  apiGetGoodsInfoList,
} from "@/request/mallManagement";
import { apiGetGoodsInfoPage } from "@/request/activityManager";

import TheImage from "@/components/TheImage";
import { Space } from "antd";
import { exportSheetTable } from "@/utils/exportTable";
import TheQueryForm from "@/components/TheQueryForm";
import TheTableExtend from "@/components/TheTableExtend";
import store from "@/store/store";
import { apiGetGoodsClassifyList } from "@/request/mallManagement";
import { getDateTime3 } from "@/utils/getDate";
import _ from "lodash";

let options = [];
class List extends React.Component {
  constructor(props) {
    super(props);
    this.queryFormRef = React.createRef();

    this.state = {
      down_loading: false,
      selectedKeys: { 1: [] },
      columns: [
        {
          title: "商品ID",
          dataIndex: "goodsId",
          key: "goodsId",
        },
        {
          title: "商品名称",
          dataIndex: "goodsName",
          key: "goodsName",
          render: (text, record) => {
            return (
              <div
                style={{
                  width: 200,
                  overflow: "hidden",
                  whiteSpace: "nowrap",
                  textOverflow: "ellipsis",
                }}
              >
                {record.goodsName}
              </div>
            );
          },
        },
        {
          title: "商品图片",
          dataIndex: "goodsShowImages",
          key: "goodsShowImages",
          render: (text) => {
            let arr = text.split(",");
            return (
              <Space>
                {arr.map((v) => {
                  return <TheImage src={v} width={80} height={80} />;
                })}
              </Space>
            );
          },
        },
        {
          title: "所属类目",
          dataIndex: "goodsClassifyName",
          key: "goodsClassifyName",
        },
        {
          title: "商品原价",
          dataIndex: "originalPrice",
          key: "originalPrice",
          render: (text) => {
            return <React.$Price price={text || 0} />;
          },
        },
        {
          title: "商品现价",
          dataIndex: "currentPrice",
          key: "currentPrice",
          render: (text) => {
            return <React.$Price price={text || 0} />;
          },
        },
        {
          title: "上次操作时间",
          dataIndex: "updateTime",
          key: "updateTime",
          render: (text, record) => {
            return record.updateTime ? record.updateTime : "/";
          },
        },
        {
          title: "状态",
          dataIndex: "goodsStatus",
          key: "goodsStatus",
          render: (text, render) => {
            let label = "";
            switch (render.goodsStatus) {
              case "Y":
                label = "上架";
                break;
              case "N":
                label = "下架";
                break;
              case "G":
                label = "管理员下架";
                break;
              default:
                label = "字段值错误";
            }
            return label;
          },
        },
      ],
      dataSource: [],
      pageData: {
        pageNo: 1,
        pageSize: 10,
      },
      total: 0,
      searchValue: {},
      newColumns: [],
      form_show: true,
      searchOption: [
        {
          field: "goodsName",
          label: "商品名称",
          placeholder: "商品名称",
          required: false,
          rules: [],
          type: "Input",
          defaultValue: "",
        },
        {
          field: "goodsId",
          label: "商品ID",
          placeholder: "商品ID",
          required: false,
          rules: [],
          type: "Input",
          options: [],
          defaultValue: "",
        },
      ],
      queryForm: {},
    };
  }
  data = () => {
    this.setState({
      selectedKeys: { 1: [] },
    });
    return this.state.selectedKeys;
  };
  //批量勾选
  onChange = (selectedRowKeys, selectedRows) => {
    let pageNo = this.state.pageData.pageNo;
    let selectedKeys = { ...this.state.selectedKeys };
    selectedKeys[pageNo] = selectedRowKeys;
    let ids = "";
    Object.values(selectedKeys).forEach((value) => {
      if (value.length > 0) {
        ids += value.toString() + ",";
      }
    });
    this.setState({
      selectedKeys,
      ids,
    });
  };
  async componentDidMount() {
    this.onColumnsFilter(this.state.columns);
    let searchParams = store.getState().searchValue;
    let { pageNo, pageSize, queryForm, pathName } = searchParams;
    if (searchParams && pageNo && pathName == "mallList") {
      this.setState(
        {
          queryForm,
          pageData: {
            pageNo: pageNo,
            pageSize: pageSize,
          },
        },
        () => {
          this.queryFormRef.onSetDefault({
            ...queryForm,
          });
          this.getData();
        }
      );
    } else {
      this.getData();
    }
  }
  getData = async (values) => {
    let { pageNo, pageSize } = this.state.pageData;
    if (values && !_.isEmpty(values.time)) {
      values.createTimeStart = getDateTime3(values.time[0]);
      values.createTimeEnd = getDateTime3(values.time[1]);
    }
    this.setState(
      {
        queryForm: values === undefined ? this.state.queryForm : { ...values },
      },
      async () => {
        let { time, ...form } = { ...this.state.queryForm };
        const params = {
          pageNo,
          pageSize,
          queryForm: { ...form, time },
        };
        // store.dispatch({
        //   type: "SaveSearchValues",
        //   data: {
        //     pathName: "mallList",
        //     ...params,
        //   },
        // });
        let res = await apiGetGoodsInfoPage({
          pageNo,
          pageSize,
          ...form,
          reviewStatus: "T",
        });
        if (res.code === 0 && res.data) {
          this.setState({
            dataSource: res.data,
            pageData: { pageNo: res.pageNo, pageSize: res.pageSize },
            total: res.totalCount,
          });
        }
      }
    );
  };

  getValue = (value) => {
    this.setState(
      { searchValue: value, pageData: { pageNo: 1, pageSize: 10 } },
      () => {
        this.getData();
      }
    );
  };
  goDetail = (goodsId) => {
    this.props.history.push(`/mall/list/detail/${goodsId}`);
  };
  goEvaluate = (goodsId, storeName, storeId) => {
    this.props.history.push(
      `/mall/list/evaluate/${goodsId}/${encodeURIComponent(
        storeName
      )}/${storeId}`
    );
  };
  pageChange = (pageNo, pageSize) => {
    this.setState(
      {
        pageData: {
          pageNo,
          pageSize,
        },
      },
      () => {
        this.getData();
      }
    );
  };
  delConfirm = () => {
    React.$confirm({
      title: "您确认删除此条商品吗?",
      onOk: async () => {},
    });
  };
  offShelf = (goodsId, goodsStatus) => {
    React.$confirm({
      title: "您确定下架该商品吗？",
      onOk: async () => {
        await apiGetGoodsInfoPutaway({ goodsId, goodsStatus });
        await this.getData();
      },
    });
  };
  putShelf = (goodsId, goodsStatus) => {
    React.$confirm({
      title: "您确定上架该商品吗？",
      onOk: async () => {
        await apiGetGoodsInfoPutaway({ goodsId, goodsStatus });
        await this.getData();
      },
    });
  };
  offRecommend = (goodsId, recommendStatus) => {
    React.$confirm({
      title: "您确定取消推荐该商品吗？",
      onOk: async () => {
        await apiGetGoodsInfoRecommend({ goodsId, recommendStatus });
        await this.getData();
      },
    });
  };
  putRecommend = (goodsId, recommendStatus) => {
    React.$confirm({
      title: "您确定推荐该商品吗？",
      onOk: async () => {
        await apiGetGoodsInfoRecommend({ goodsId, recommendStatus });
        await this.getData();
      },
    });
  };
  //表格导出
  async toExportTable() {
    this.setState({ down_loading: true });
    await apiGetGoodsInfoList({ ...this.state.queryForm, reviewStatus: "T" })
      .then((res) => {
        if (res.code === 0 && res.data.length > 0) {
          let tH_data = [
            {
              title: "商城商品列表",
              prop: "",
              children: [
                { prop: "goodsId", title: "商品ID" },
                { prop: "goodsName", title: "商品名称" },
                { prop: "classifyName", title: "所属类目" },
                { prop: "storeName", title: "所属商家" },
                { prop: "createTime", title: "申请时间" },
                { prop: "goodsStatus", title: "状态" },
                { prop: "recommendStatus", title: "推荐" },
                { prop: "materialId", title: "物料ID" },
                { prop: "goodsKeyValue", title: "规格" },
                {
                  prop: "skuOriginalPrice",
                  title: "原价",
                  valueType: "number",
                },
                { prop: "skuCurrentPrice", title: "现价", valueType: "number" },
                { prop: "skuStock", title: "库存", valueType: "number" },
              ],
            },
          ];
          let tB_data = res.data.map((item) => {
            return {
              goodsId: item.goodsId,
              goodsName: item.goodsName,
              classifyName: item.classifyName,
              storeName: item.storeName,
              createTime: item.createTime,
              goodsStatus: this.getGoodsStatus(item.goodsStatus),
              recommendStatus: this.getRecommendStatus(item.recommendStatus),
              materialId: item.materialId,
              goodsKeyValue: item.goodsKeyValue,
              skuOriginalPrice: (Number(item.skuOriginalPrice) / 100).toFixed(
                2
              ),
              skuCurrentPrice: (Number(item.skuCurrentPrice) / 100).toFixed(2),
              skuStock: item.skuStock,
            };
          });

          this.setState({ down_loading: false });
          exportSheetTable({
            fileName: "商城商品列表",
            tH_data: tH_data,
            tB_data: tB_data,
            isSheet: true,
            merge: true,
            mergeProp: [
              "goodsId",
              "goodsName",
              "classifyName",
              "storeName",
              "createTime",
              "goodsStatus",
              "recommendStatus",
            ],
          });
        } else {
          React.$message({
            type: "warning",
            content: "导出操作失败,请重试",
          });
          this.setState({ down_loading: false });
        }
      })
      .catch((err) => {
        React.$message({
          type: "warning",
          content: "导出操作失败,请重试",
        });
        this.setState({ down_loading: false });
      });
  }
  getRecommendStatus(text) {
    let label = "";
    switch (text) {
      case "Y":
        label = "是";
        break;
      case "N":
        label = "否";
        break;
      default:
        label = "字段值错误";
    }
    return label;
  }

  getGoodsStatus(text) {
    let label = "";
    switch (text) {
      case "Y":
        label = "上架";
        break;
      case "N":
        label = "下架";
        break;
      case "G":
        label = "管理员下架";
        break;
      default:
        label = "字段值错误";
    }
    return label;
  }
  onFinishSearch() {
    let values = this.formRef_search.current.getFieldsValue();
    this.setState(
      {
        code: values.code,
      },
      () => {
        this.pageChange(1, 10);
      }
    );
  }
  onReset() {
    this.setState(
      {
        queryForm: {},
      },
      () => {
        this.getData();
      }
    );
  }
  onColumnsFilter(value) {
    this.setState({
      newColumns: value,
    });
  }
  onFormSearch(values) {
    this.setState(
      {
        pageData: { pageNo: 1, pageSize: 10 },
      },
      () => {
        this.getData(values);
      }
    );
  }

  render() {
    const {
      columns,
      dataSource,
      pageData: { pageNo, pageSize },
      total,
      down_loading,
      form_show,
      searchOption,
      newColumns,
      selectedKeys,
    } = this.state;
    const rowSelection = {
      selectedRowKeys: selectedKeys[pageNo],
      onChange: this.onChange,
    };
    return (
      <div className={"p-layout-box commodity-content"}>
        <TheQueryForm
          ref={(ref) => (this.queryFormRef = ref)}
          show={form_show}
          option={searchOption}
          onReset={() => this.onReset()}
          onGetValues={(values) => this.onFormSearch(values)}
        ></TheQueryForm>
        {/* <TheTableExtend
          columns={columns}
          onFormTrigger={() =>
            this.setState({ form_show: !this.state.form_show })
          }
          onTableRefresh={() => this.getData()}
          onColumnsFilter={(value) => this.onColumnsFilter(value)}
        ></TheTableExtend> */}
        <div className="p-layout-content-pagination">
          <TheTable
            columns={newColumns}
            dataSource={dataSource}
            scroll={{ x: "max-content", y: "43vh" }}
            rowSelection={rowSelection}
            rowKey={(record) => record}
          />
          <ThePagination
            pageNo={pageNo}
            pageSize={pageSize}
            total={total}
            pageChange={this.pageChange}
          />
        </div>
      </div>
    );
  }
}

export default List;
